package com.lap.oauth2.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.session.HttpSessionEventPublisher;

/**
 * 权限配置
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
@Slf4j
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    @Order(2)
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        log.info("Initializer Security filter chain");
        http.csrf(Customizer.withDefaults())
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/login", "/css/*")
                        .permitAll()
                        .anyRequest()
                        .authenticated())
                .formLogin(form -> form.loginPage("/login"));

        return http.build();
    }

    @Bean
    UserDetailsService userDetailsService() {
        UserDetails u1 = User
                .withUsername("lao")
                .password("{noop}lao")
                .roles("USER")
                .authorities("aaa")
                .build();
        UserDetails u2 = User
                .withUsername("user")
                .password("{noop}user")
                .roles("USER")
                .authorities("bbb")
                .build();
        return new InMemoryUserDetailsManager(u1, u2);
    }

    @Bean
    SessionRegistry sessionRegistry() {
        log.info("Initializer session registry");
        return new SessionRegistryImpl();
    }

    @Bean
    HttpSessionEventPublisher httpSessionEventPublisher() {
        log.info("Initializer session publisher");
        return new HttpSessionEventPublisher();
    }

}
